package com.cyf.plc.handler

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import com.cyf.library.util.loge
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * 自定义异常处理类
 */
class CrashHandler(var mContext: Context) : Thread.UncaughtExceptionHandler {

    private val PATH = Environment.getExternalStorageDirectory().absolutePath
    private val FILE_NAME_SUFFIX = ".trace"

    override fun uncaughtException(t: Thread, e: Throwable) {
        //判断SD卡是否存在
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return
        }
        GlobalScope.launch {
            withContext(Dispatchers.IO) {
                try {
                    val time: String =
                        SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault()).format(Date())
                    val file = File(PATH + File.separator.toString() + time + FILE_NAME_SUFFIX)
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    "Write error log.".loge()
                    //往文件中写入数据
                    val pw = PrintWriter(BufferedWriter(FileWriter(file)))
                    pw.println(time)
                    pw.println(appendPhoneInfo(mContext))
                    e.printStackTrace(pw)
                    pw.close()
                } catch (e1: IOException) {
                    e1.printStackTrace()
                } catch (e1: PackageManager.NameNotFoundException) {
                    e1.printStackTrace()
                }
            }
        }
    }

    private fun appendPhoneInfo(mContext: Context): String {
        val pm: PackageManager = mContext.getPackageManager()
        val pi: PackageInfo =
            pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES)
        val sb = StringBuilder()
        //App版本
        sb.append("App Version: ")
        sb.append(pi.versionName)
        sb.append("_")
        sb.append("${pi.versionCode}".trimIndent())

        //Android版本号
        sb.append("OS Version: ")
        sb.append(Build.VERSION.RELEASE)
        sb.append("_")
        sb.append("${Build.VERSION.SDK_INT}".trimIndent())

        //手机制造商
        sb.append("Vendor: ")
        sb.append(Build.MANUFACTURER.trimIndent())
        //手机型号
        sb.append("Model: ")
        sb.append(Build.MODEL.trimIndent())

        //CPU架构
        sb.append("CPU: ")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            sb.append(Arrays.toString(Build.SUPPORTED_ABIS))
        } else {
            sb.append(Build.CPU_ABI)
        }
        return sb.toString()
    }

}